package com.sunlee.common.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sunlee.common.core.entity.PageData;
import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.service.dao.ThirdProductCategoryMappingDao;
import com.sunlee.common.service.dto.*;
import com.sunlee.common.service.entity.ProductCategoryMappingEntity;
import com.sunlee.common.service.entity.ThirdProductCategoryMappingEntity;
import com.sunlee.common.service.entity.ThirdProductEntity;
import com.sunlee.common.service.service.ThirdCategoryService;
import com.sunlee.common.service.service.ThirdProductCategoryMappingService;
import com.sunlee.common.service.service.ThirdProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 第三方商品分类映射表
 *
 * @author sunlee
 * @date 2023-03-04
 */
@Service
@Slf4j
public class ThirdProductCategoryMappingServiceImpl
        extends CrudServiceImpl<ThirdProductCategoryMappingDao, ThirdProductCategoryMappingEntity, ThirdProductCategoryMappingDTO>
        implements ThirdProductCategoryMappingService {

    @Autowired
    private ThirdCategoryService thirdCategoryService;

    @Override
    public PageData<ThirdProductDTO> pageRelatedByCid(Map<String, Object> params, long cid) {
        IPage<ThirdProductDTO> page = baseDao.pageRelatedByCid(getPage(params, null, false), cid);
        return new PageData<>(page.getRecords(), page.getTotal());
    }

    @Override
    public PageData<ThirdCategoryDTO> pageRelatedByPid(Map<String, Object> params, long pid) {
        PageData<ThirdCategoryDTO> thirdCategoryPage = thirdCategoryService.pageOwn(params);

        List<ThirdCategoryDTO> allCategory = thirdCategoryPage.getList();

        List<ThirdProductCategoryMappingEntity> chooseCategory = list(new LambdaQueryWrapper<ThirdProductCategoryMappingEntity>()
                .eq(ThirdProductCategoryMappingEntity::getProductId, pid));

        allCategory.forEach(all ->
                all.getChildren().forEach(children -> {
                            boolean res = chooseCategory.stream().anyMatch(choose -> children.getPid() != 0 && choose.getCategoryId().equals(children.getId()));
                            children.setChoose(res);
                            if (res && Objects.isNull(all.getChoose())) {
                                all.setChoose(true);
                            }

                        }
                )

        );

        return thirdCategoryPage;
    }

    @Override
    public Integer deleteByCidAndPidBatch(Long categoryId, Long[] ids) {
        return baseDao.delete(new LambdaQueryWrapper<ThirdProductCategoryMappingEntity>()
                .eq(ThirdProductCategoryMappingEntity::getCategoryId, categoryId)
                .in(ThirdProductCategoryMappingEntity::getProductId, Arrays.asList(ids)));
    }

    @Override
    public void deleteByPidBatch(List<Long> pIds) {
        baseDao.delete(new LambdaQueryWrapper<ThirdProductCategoryMappingEntity>().in(ThirdProductCategoryMappingEntity::getProductId, pIds));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editByPid(Long productId, Long[] cIds) {

        // 需保存的分类
        List<Long> editList = Arrays.asList(cIds);

        List<ThirdProductCategoryMappingEntity> existMappingList = list(new LambdaQueryWrapper<ThirdProductCategoryMappingEntity>()
                .eq(ThirdProductCategoryMappingEntity::getProductId, productId));

        // 数据库已存在的分类
        List<Long> existList = existMappingList.stream().map(ThirdProductCategoryMappingEntity::getCategoryId).collect(Collectors.toList());

        // 删除数据库不需要保存的
        int deleteRes = baseDao.delete(new LambdaQueryWrapper<ThirdProductCategoryMappingEntity>()
                .eq(ThirdProductCategoryMappingEntity::getProductId, productId)
                .notIn(ThirdProductCategoryMappingEntity::getCategoryId, existList));

        // 需保存的分类过滤掉已存在的分类，剩下的需要保存
        editList.removeAll(existList);

        List<ThirdProductCategoryMappingEntity> saveEntityList = editList.stream().map(cId -> {
            ThirdProductCategoryMappingEntity entity = new ThirdProductCategoryMappingEntity();
            entity.setCategoryId(cId);
            entity.setProductId(productId);
            return entity;
        }).collect(Collectors.toList());

        boolean saveRes = saveBatch(saveEntityList);

        if (deleteRes < 1 || !saveRes) {
            throw new BusinessException("第三方商品关联分类失败: " + productId);
        }
    }

    @Override
    public void deleteByPIds(List<Long> pIds) {
        baseDao.delete(new LambdaQueryWrapper<ThirdProductCategoryMappingEntity>()
                .in(ThirdProductCategoryMappingEntity::getProductId, pIds));
    }

    @Override
    public Integer deleteByPidAndCidBatch(Long productId, Long[] ids) {
        return baseDao.delete(new LambdaQueryWrapper<ThirdProductCategoryMappingEntity>()
                .eq(ThirdProductCategoryMappingEntity::getProductId, productId)
                .in(ThirdProductCategoryMappingEntity::getCategoryId, Arrays.asList(ids)));
    }
}




